/**
 * LICENSE
 * 
 * Copyright (c) 2010, Maks Slesarenko
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   1 Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   2 Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * The views and conclusions contained in the software and documentation are 
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of Maks Slesarenko.
 */
(function($){
    $.widget("wheels.dashboard", {
        //Set the default values, use comma to separate the settings, example:
        options: {
            widgetClass: 'dashboard-widget',
            editable: false,
            draggable: false
        },
        
        _current:{
            x1: null,
            x2: null,
            y1: null,
            y2: null
        },

        _create: function() {

            var _self = this;
            var $container = $(this.element);
            
            if ('static' == $container.css('position')) {
                $container.css('position', 'relative');
            }
            
            var x1,x2,y1,y2, box;

            $('#dialog').dialog({
                autoOpen: false,
                modal: true,
                width: 400,
                buttons: {
                    "Save": function() {
                        var resource = $('input[name=resource]').val();
                        if (!resource) {
                            return;
                        }
                        var el = $('.dashboard-widget.ui-state-active');
                        var content = el.children('.widget-content');

                        if (!content.length) {
                            if ($('input[name=iframe]').is(':checked')) {
                                content = $('<iframe>', {'src': resource});
                            } else {
                                content = $('<div>');
                                content.load(resource);
                            }
                            el.append(content.attr('class', 'widget-content'));
                        }
                        el.attr('resource', $('input[name=resource]').val())
                          .attr('id', $('input[name=id]').val())
                          .attr('title', $('input[name=title]').val());

                        $(this).dialog("close");
                    },
                    "Cancel": function() {
                        $(this).dialog("close");
                    }
                },
                open: function(){
                    var el = $('.dashboard-widget.ui-state-active')
                    $('input[name=title]').val(el.attr('title'));
                    $('input[name=id]').val(el.attr('id'));
                    $('input[name=resource]').val(el.attr('resource'));
                },
                beforeClose: function(){
                    $('input[name=title]').add($('input[name=id]'))
                                         .add($('input[name=resource]'))
                                         .val('');

                    var widget = $('.dashboard-widget.ui-state-active');
                    if (widget.children('.widget-content').length) {
                        widget.removeClass('ui-state-active');
                    } else {
                        widget.remove();
                    }
                }
            });
            $container.delegate('.dashboard-widget', 'click', function(e) {
                $('.dashboard-widget').removeClass('ui-state-active');
                $(this).addClass('ui-state-active');
                $('#dialog').dialog('open');
            }).delegate('.dashboard-widget', 'hover', function(e){
                if (e.type == 'mouseenter') {
                    $(this).addClass('ui-state-hover').prepend($('<div>', {
                        'html': '<h3 class="ui-widget-header ui-corner-all ui-helper-clearfix"><span>title</span><a class="ui-corner-all"><span class="ui-icon ui-icon-closethick removeWidget">close</span></a></h3>',
                        'class': 'header'
                    }));
                } else {
                    $(this).removeClass('ui-state-hover').children('div.header').remove();
                }
            }).delegate('.removeWidget', 'click', function(e){
                var el = $(this).parent().parent().parent().parent();
                e.stopPropagation();
                if (confirm('Are you sure?')) {
                    el.remove();
                }
            });

            $container.mousedown(function(e) {

                if ($('.dashboard-widget:hover').length) {
                    return true;
                }
                box = $('<div class="dashboard-widget" style="border:1px #00F solid;position:absolute;">').hide();
                //box.append($('<iframe>'));
                box.resizable().draggable();

                x1 = e.pageX;
                y1 = e.pageY;

                box.css({
                    top: e.pageY , //offsets
                    left: e.pageX //offsets
                }).fadeIn();
            });
            $container.mousemove(function(e) {
                if (box) {
                    if (!box.parent().length) {
                        $('#content').append(box);
                    }
                    box.css({
                        width:Math.abs(e.pageX - x1), //offsets
                        height:Math.abs(e.pageY - y1) //offsets
                    }).fadeIn();
                }
            });

            $container.mouseup(function() {
                if (box && box.parent().length) {
                    $('#dialog').dialog('open');
                    box.addClass('ui-state-active');
                }
                box = null;
            });
        },
        
        add: function(resource, title, id, iframe, save) {
            if (!resource) {
                throw 'Error resource';
            }
            if (!id) {
                var i = 1;
                var newId = id + '-' + i;
                while (!document.getElementById(newId).length) {
                    i++;
                }
                id = newId;
                
                var $widget = $('<div>');
            }
            
            if (save) {
                
            }
            
            $widget.attr('id', id)
                   .attr('title', title);

            $content = $widget.children('.widget-content');
            
            var tagName = 'div';
            if (iframe) {
                tagName = 'iframe';
            }
            if (!$content.length || !$content.is(tagName)) {
                $content.remove();
            
                $content = $('<' + tagName + '>', {'class': 'widget-content'});
                
                if (iframe) {
                    $content.attr('src', resource);
                } else {
                    $content.load(resource);
                }
            }
        }
    });
})(jQuery);